package com.icetec.iceintel.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.icetec.R;
import com.icetec.iceintel.database.AlarmConfigSqlHelper;
import com.icetec.iceintel.framework.IceBaseActivity;
import com.icetec.iceintel.model.Alarm;
import com.icetec.iceintel.model.AlarmPreference;
import com.icetec.iceintel.netrequest.InstrutionSender;
import com.icetec.iceintel.service.AlarmServiceBroadcastReciever;
import com.icetec.iceintel.ui.adapter.AlarmPreferenceListAdapter;
import com.icetec.iceintel.utility.ToastUtility;

import java.util.ArrayList;
import java.util.Calendar;


/**
 * Created by amo on 2015/3/12.
 * 单个闹钟详细的设置界面
 */

public class AlarmModificationActivity extends IceBaseActivity {

    private Alarm alarm;
    private MediaPlayer mediaPlayer;

    private ListAdapter listAdapter;
    private ListView listView;

    AlarmConfigSqlHelper alarmConfigSqlHelper;

    InstrutionSender instrutionSender;
    TextView backTv;
    TextView saveTv;
    TextView titleTv;

    ArrayList<Alarm> alarmArraylist;

    TimePicker timePicker;
    Button deleteButton;

    final int REQUEST_CODE_SINGLELIGHT = 1;
    final int SINGLE_DEVICE_SUCESS = 1;

    boolean deviceSelected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_preferences);


        backTv = (TextView) findViewById(R.id.alarm_preferences_back_tv);
        saveTv = (TextView) findViewById(R.id.alarm_preferences_save_tv);
        timePicker = (TimePicker) findViewById(R.id.alarm_preferences_timePicker);
        deleteButton = (Button) findViewById(R.id.alarm_preferences_delete_btn);
        listView = (ListView) findViewById(android.R.id.list);
        titleTv = (TextView) findViewById(R.id.alarm_preferences_title_tv);


        timePicker.setIs24HourView(true);
        instrutionSender = new InstrutionSender();


        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(AlarmModificationActivity.this);
                dialog.setTitle(R.string.delete);
                dialog.setMessage(R.string.delete__ensure);
                dialog.setPositiveButton(R.string.ensure, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (getAlarm().getId() < 1) {
                            // Alarm not saved
                        } else {
                            alarmConfigSqlHelper.deleteEntry(alarm);
                            alarm.setAlarmActive(false);
                            instrutionSender.setAlarm(alarm);
                            callMathAlarmScheduleService();
                        }

                        finish();
                    }
                });
                dialog.setNegativeButton(R.string.cancel, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();

            }
        });


        //获取从外部传入的闹钟实体,以此来判断，这个闹钟是新建的，还是进入了编辑界面

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.containsKey("alarm")) {
            setAlarm((Alarm) bundle.getSerializable("alarm"));
            if (getAlarm().getAlarmType() == Alarm.AlarmType.AWAKE) {

                titleTv.setText(R.string.alarm_awake);

            } else {

                titleTv.setText(R.string.alarm_sleep);
            }

            deviceSelected = true;

        } else {
            setAlarm(new Alarm());
            deleteButton.setVisibility(View.GONE);
        }

        if (bundle != null && bundle.containsKey("type")) {

            if (bundle.get("type") == Alarm.AlarmType.AWAKE) {

                titleTv.setText(R.string.alarm_awake);
                getAlarm().setAlarmType(Alarm.AlarmType.AWAKE);
            } else {

                titleTv.setText(R.string.alarm_sleep);
                getAlarm().setAlarmType(Alarm.AlarmType.SLEEP);
            }

        }


        if (bundle != null && bundle.containsKey("adapter")) {
            setListAdapter((AlarmPreferenceListAdapter) bundle.getSerializable("adapter"));
        } else {
            setListAdapter(new AlarmPreferenceListAdapter(this, getAlarm()));
        }

        //获取闹钟的数据库实例
        alarmConfigSqlHelper = new AlarmConfigSqlHelper();

        alarmArraylist = alarmConfigSqlHelper.getAllAlarm(getAlarm().getAlarmType());

        backTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        saveTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!deviceSelected) {
                    ToastUtility.show(R.string.please_select_atlseat_once);
                    return;
                } else {
                    //如果选了设备 那么就就验证这个设备在这个时间点是否已经设置过了闹钟


                    for (Alarm tempAlarm : alarmArraylist) {
                        if (tempAlarm.getAlarmMAC().equals(alarm.getAlarmMAC()
                        ) && tempAlarm.getAlarmTime().get(Calendar.HOUR_OF_DAY) == alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY)
                                && tempAlarm.getAlarmTime().get(Calendar.MINUTE) == alarm.getAlarmTime().get(Calendar.MINUTE)) {

                            ToastUtility.show(R.string.modify_alarm_time);
                            return;


                        }

                    }

                }

                //如果是新闹钟，则增加
                if (getAlarm().getId() < 1) {

                    allocatePort(alarm);

                    if (alarmConfigSqlHelper.addAlarm(getAlarm()) != -1) {
                        ToastUtility.show(alarm.getTimeUntilNextAlarmMessage());
                        ToastUtility.show("分配了" + alarm.getAlarmPort() + "闹钟端口");

                        instrutionSender.setAlarm(alarm);

                        callMathAlarmScheduleService();
                        finish();
                    }

                }
                //否则则更新即可
                else {
                    if (alarmConfigSqlHelper.update(getAlarm()) != -1) {
                        ToastUtility.show(alarm.getTimeUntilNextAlarmMessage());
                        ToastUtility.show(getResources().getString(R.string.distribute)
                                + alarm.getAlarmPort()
                                + getResources().getString(R.string.alarm_port));

                        instrutionSender.setAlarm(alarm);

                        callMathAlarmScheduleService();
                        finish();

                    }
                }


            }
        });


        //将闹钟控件设置为当前时间
        timePicker.setCurrentHour(alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(alarm.getAlarmTime().get(Calendar.MINUTE));
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

                Calendar newAlarmTime = Calendar.getInstance();
                newAlarmTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                newAlarmTime.set(Calendar.MINUTE, minute);
                newAlarmTime.set(Calendar.SECOND, 0);
                alarm.setAlarmTime(newAlarmTime);

            }
        });


        //闹钟设置界面,ListView的设置项，使用AlertDialog.Builder alert构建不同的配置项
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> l, View v, int position, long id) {
                final AlarmPreferenceListAdapter alarmPreferenceListAdapter = (AlarmPreferenceListAdapter) getListAdapter();
                final AlarmPreference alarmPreference = (AlarmPreference) alarmPreferenceListAdapter.getItem(position);

                AlertDialog.Builder alert;

                v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);

                switch (alarmPreference.getType()) {
                    //如果是选择灯具，则打开activity
                    case ACTIVITY:
                        startActivityForResult(new Intent(AlarmModificationActivity.this, SelectDeviceActivity.class), REQUEST_CODE_SINGLELIGHT);
                        break;

                    //是否的选项

                    case BOOLEAN:
                        CheckedTextView checkedTextView = (CheckedTextView) v;
                        boolean checked = !checkedTextView.isChecked();
                        ((CheckedTextView) v).setChecked(checked);
                        switch (alarmPreference.getKey()) {

                            //是否激活这个闹钟
                            case ALARM_ACTIVE:
                                alarm.setAlarmActive(checked);
                                break;

                            //这个闹钟是否震动

                            case ALARM_VIBRATE:
                                alarm.setVibrate(checked);
                                if (checked) {
                                    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                                    vibrator.vibrate(1000);
                                }
                                break;
                        }
                        alarmPreference.setValue(checked);
                        break;

                    case STRING:


                        //设置闹钟的提示
                        alert = new AlertDialog.Builder(AlarmModificationActivity.this);

                        alert.setTitle(alarmPreference.getTitle());
                        // alert.setMessage(message);
                        // Set an EditText view to get user input
                        final EditText input = new EditText(AlarmModificationActivity.this);

                        input.setText(alarmPreference.getValue().toString());

                        alert.setView(input);
                        alert.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                alarmPreference.setValue(input.getText().toString());

                                if (alarmPreference.getKey() == AlarmPreference.Key.ALARM_NAME) {
                                    alarm.setAlarmName(alarmPreference.getValue().toString());
                                }

                                alarmPreferenceListAdapter.setAlarm(getAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }
                        });
                        alert.show();
                        break;
                    case LIST:
                        alert = new AlertDialog.Builder(AlarmModificationActivity.this);

                        alert.setTitle(alarmPreference.getTitle());
                        // alert.setMessage(message);

                        CharSequence[] items = new CharSequence[alarmPreference.getOptions().length];
                        for (int i = 0; i < items.length; i++)
                            items[i] = alarmPreference.getOptions()[i];

                        alert.setItems(items, new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (alarmPreference.getKey()) {
                                    //选择闹钟类型的表
                                    case ALARM_TYPE:
                                        Alarm.AlarmType d = Alarm.AlarmType.values()[which];
                                        alarm.setAlarmType(d);
                                        break;

                                    //选择闹钟铃声的表
                        /*	case ALARM_TONE:
								alarm.setAlarmTonePath(alarmPreferenceListAdapter.getAlarmTonePaths()[which]);
								if (alarm.getAlarmTonePath() != null) {
									if (mediaPlayer == null) {
										mediaPlayer = new MediaPlayer();
									} else {
										if (mediaPlayer.isPlaying())
											mediaPlayer.stop();
										mediaPlayer.reset();
									}
									try {
										// mediaPlayer.setVolume(1.0f, 1.0f);
										mediaPlayer.setVolume(0.2f, 0.2f);
										mediaPlayer.setDataSource(AlarmPreferencesActivity.this, Uri.parse(alarm.getAlarmTonePath()));
										mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
										mediaPlayer.setLooping(false);
										mediaPlayer.prepare();
										mediaPlayer.start();

										// Force the mediaPlayer to stop after 3
										// seconds...
										if (alarmToneTimer != null)
											alarmToneTimer.cancel();
										alarmToneTimer = new CountDownTimer(3000, 3000) {
											@Override
											public void onTick(long millisUntilFinished) {

											}

											@Override
											public void onFinish() {
												try {
													if (mediaPlayer.isPlaying())
														mediaPlayer.stop();
												} catch (Exception e) {

												}
											}
										};
										alarmToneTimer.start();
									} catch (Exception e) {
										try {
											if (mediaPlayer.isPlaying())
												mediaPlayer.stop();
										} catch (Exception e2) {

										}
									}
								}
								break;*/
                                    default:
                                        break;
                                }
                                alarmPreferenceListAdapter.setAlarm(getAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }

                        });

                        alert.show();
                        break;
                    case MULTIPLE_LIST:
                        alert = new AlertDialog.Builder(AlarmModificationActivity.this);

                        alert.setTitle(alarmPreference.getTitle());
                        // alert.setMessage(message);

                        CharSequence[] multiListItems = new CharSequence[alarmPreference.getOptions().length];
                        for (int i = 0; i < multiListItems.length; i++)
                            multiListItems[i] = alarmPreference.getOptions()[i];

                        boolean[] checkedItems = new boolean[multiListItems.length];
                        for (Alarm.Day day : getAlarm().getDays()) {
                            checkedItems[day.ordinal()] = true;
                        }
                        alert.setMultiChoiceItems(multiListItems, checkedItems, new OnMultiChoiceClickListener() {

                            @Override
                            public void onClick(final DialogInterface dialog, int which, boolean isChecked) {

                                Alarm.Day thisDay = Alarm.Day.values()[which];

                                if (isChecked) {
                                    alarm.addDay(thisDay);
                                } else {
                                    // Only remove the day if there are more than 1
                                    // selected
                                    if (alarm.getDays().length > 1) {
                                        alarm.removeDay(thisDay);
                                    } else {
                                        // If the last day was unchecked, re-check
                                        // it
                                        ((AlertDialog) dialog).getListView().setItemChecked(which, true);
                                    }
                                }

                            }
                        });
                        alert.setOnCancelListener(new OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                alarmPreferenceListAdapter.setAlarm(getAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();

                            }
                        });
                        alert.show();
                        break;
			/*	case TIME:
					TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmPreferencesActivity.this, new OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
							Calendar newAlarmTime = Calendar.getInstance();
							newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
							newAlarmTime.set(Calendar.MINUTE, minutes);
							newAlarmTime.set(Calendar.SECOND, 0);
							alarm.setAlarmTime(newAlarmTime);
							alarmPreferenceListAdapter.setAlarm(getAlarm());
							alarmPreferenceListAdapter.notifyDataSetChanged();
						}
					}, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY), alarm.getAlarmTime().get(Calendar.MINUTE), true);
					timePickerDialog.setTitle(alarmPreference.getTitle());
					timePickerDialog.show();*/
                    default:
                        break;
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_alarm, menu);
        menu.findItem(R.id.menu_item_new).setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            //对于储存的对象，如果ID是小于1，则这个是新创建的闹钟，就添加，否则就更新即可
            case R.id.menu_item_save:
                if (getAlarm().getId() < 1) {
                    alarmConfigSqlHelper.addAlarm(getAlarm());
                } else {
                    alarmConfigSqlHelper.update(getAlarm());
                }
                callMathAlarmScheduleService();
                //Toast.makeText(AlarmModificationActivity.this, getAlarm().getTimeUntilNextAlarmMessage(), Toast.LENGTH_LONG).show();
                finish();
                break;

            case R.id.menu_item_delete:
                AlertDialog.Builder dialog = new AlertDialog.Builder(AlarmModificationActivity.this);
                dialog.setTitle(R.string.delete);
                dialog.setMessage(R.string.delete__ensure);
                dialog.setPositiveButton(R.string.ensure, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (getAlarm().getId() < 1) {
                            // Alarm not saved
                        } else {
                            alarmConfigSqlHelper.deleteEntry(alarm);

                            alarm.setAlarmActive(false);
                            instrutionSender.setAlarm(alarm);

                            callMathAlarmScheduleService();
                        }
                        finish();
                    }
                });
                dialog.setNegativeButton(R.string.cancel, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private CountDownTimer alarmToneTimer;


    //保存实例的状态，当离开这个界面的时候保存之前的设置
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //outState.putSerializable("alarm", getAlarm());
        //	outState.putSerializable("adapter", (AlarmPreferenceListAdapter) getListAdapter());
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    public Alarm getAlarm() {
        return alarm;
    }

    public void setAlarm(Alarm alarm) {
        this.alarm = alarm;
    }

    public ListAdapter getListAdapter() {
        return listAdapter;
    }

    public void setListAdapter(ListAdapter listAdapter) {
        this.listAdapter = listAdapter;
        listView.setAdapter(listAdapter);

    }


    //发送闹钟调度服务广播
    protected void callMathAlarmScheduleService() {
        Intent AlarmServiceIntent = new Intent(this, AlarmServiceBroadcastReciever.class);
        sendBroadcast(AlarmServiceIntent, null);
    }


    //接受选择设备后的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == SINGLE_DEVICE_SUCESS) {
            deviceSelected = true;
            String mac = data.getExtras().getString("MAC");
            getAlarm().setAlarmMAC(mac);
            ((AlarmPreferenceListAdapter) listAdapter).setAlarm(getAlarm());
            ((AlarmPreferenceListAdapter) listAdapter).notifyDataSetChanged();

        }


    }

    //输入一个闹钟，为这个闹钟分配闹钟端口，分配成功返回真，否则返回flase

    public static boolean allocatePort(Alarm alarm) {
        ArrayList<Alarm> alarmArrayList = new AlarmConfigSqlHelper().getAllAlarm(alarm.getAlarmType());
        boolean[] portArray = new boolean[10];
        boolean allocated = false;

        //初始化
        for (int i = 0; i < 10; i++) {
            portArray[i] = false;
        }

        //填充已分配端口情况
        for (Alarm alarmIns : alarmArrayList) {
            if (alarmIns.getAlarmMAC().equals(alarm.getAlarmMAC()) && alarmIns.getAlarmActive() && alarm.getAlarmType() == alarmIns.getAlarmType()) {

                Log.i("闹钟端口分配", "端口是" + alarmIns.getAlarmPort());
                portArray[alarmIns.getAlarmPort()] = true;
            }
        }
        //分配端口，顺序
        for (int i = 0; i < 10; i++) {
            if (!portArray[i]) {
                alarm.setAlarmPort(i);
                allocated = true;
                break;
            }
        }
        return allocated;


    }


}
